
package cn.eveo.trypagerindicator;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IntDef;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


/**
 * 互相伤害指示栏
 **/
public class TryPagerIndicator extends HorizontalScrollView {

    public interface IconProvider {
        Drawable getIcon();
    }

    private List<Tab> tabList = new ArrayList<>();

    private final PageListener pageListener = new PageListener();

    private LinearLayout.LayoutParams wrapTabLayoutParams;
    private LinearLayout.LayoutParams expandedTabLayoutParams;

    private LinearLayout tabsContainer;    //scrollView的第一个布局必须是LinearLayout
    private ViewPager pager;    //关联的viewpager

    private int currentPosition = 0;
    private float currentPositionOffset = 0f;
    private int selectPosition = 0;

    private Paint rectPaint;
    private Paint dividerPaint;

    private int indicatorColor = 0xFF666666;
    private int underlineColor = 0xFF000000;
    private int dividerColor = 0x1A000000;

    private boolean isExpand = false;    //表示每个textview是否等分
    private boolean isSame = false;    //表示指示条的长度是否与标题字体的长度一样
    private boolean textAllCaps = false;    //是否大写

    private int scrollOffset = 52;
    private int indicatorHeight = 5;//指示条高度
    private int underlineHeight = 2;//底线高度

    private int dividerTopBottomPadding = 12;
    private int horizontalPadding = 24;//leftpadding、rightpadding
    private int verticalPadding = 10;//toppadding、bottomdding
    private int dividerWidth = 1;

    private int tabTextSize = 12;
    private int tabTextColor = 0xFF666666;
    private int tabSelectTextColor = 0xFF000000;

    private int lastScrollX = -1;
    private int tabBackgroundResId;
    private Locale locale;    //配置语言环境（国际化）

    /**
     * 使用注解代替枚举，使用者只能调用定义的标志，而不能直接填入数字
     */
    public static final int ICON_ABOVE_TEXT = 1;
    public static final int ICON_BELOW_TEXT = 2;
    private int tabRule = ICON_ABOVE_TEXT;

    @IntDef(flag = true, value = {ICON_ABOVE_TEXT, ICON_BELOW_TEXT})
    @Retention(RetentionPolicy.SOURCE)
    public @interface TabRule {
    }

    public void setTabRule(@TabRule int tabRule) {
        this.tabRule = tabRule;
    }

    public TryPagerIndicator(Context context) {
        this(context, null);
    }

    public TryPagerIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TryPagerIndicator(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        setFillViewport(true);//子布局(即LinearLayout)充满HorizontalScrollView的宽
        setWillNotDraw(false);//保证以后重新onDraw()方法被调用

        tabsContainer = new LinearLayout(context);
        tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
        tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        addView(tabsContainer);

        //初始化自定义属性
        obtainAttrs(context, attrs, defStyle);

        //滑动条和底线同用一支paint
        rectPaint = new Paint();
        rectPaint.setAntiAlias(true);
        rectPaint.setStyle(Style.FILL);

        //分隔线
        dividerPaint = new Paint();
        dividerPaint.setAntiAlias(true);
        dividerPaint.setStrokeWidth(dividerWidth);

        //textview不等分屏宽的LayoutParams
        wrapTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.MATCH_PARENT);
        //textvie等分屏宽的LayoutParams
        expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);

        if (locale == null) {
            locale = getResources().getConfiguration().locale;
        }
    }

    private void obtainAttrs(Context context, AttributeSet attrs, int defStyle) {
        DisplayMetrics dm = getResources().getDisplayMetrics();

        //init default value
        scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset,
                dm);
        indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                indicatorHeight, dm);
        underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                underlineHeight, dm);
        dividerTopBottomPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dividerTopBottomPadding, dm);
        horizontalPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, horizontalPadding, dm);
        dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth,
                dm);
        tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);

        // get custom attrs
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TryPagerIndicator);

        tabTextSize = a.getDimensionPixelSize(R.styleable.TryPagerIndicator_tryTextSize, tabTextSize);
        tabTextColor = a.getColor(R.styleable.TryPagerIndicator_tryTextColor, tabTextColor);
        tabSelectTextColor = a.getColor(R.styleable.TryPagerIndicator_trySelectTextColor, tabSelectTextColor);
        indicatorColor = a.getColor(R.styleable.TryPagerIndicator_tryIndicatorColor, indicatorColor);
        underlineColor = a.getColor(R.styleable.TryPagerIndicator_tryUnderlineColor, underlineColor);
        dividerColor = a.getColor(R.styleable.TryPagerIndicator_tryDividerColor, dividerColor);
        indicatorHeight = a.getDimensionPixelSize(R.styleable.TryPagerIndicator_tryIndicatorHeight, indicatorHeight);
        underlineHeight = a.getDimensionPixelSize(R.styleable.TryPagerIndicator_tryUnderlineHeight, underlineHeight);
        dividerTopBottomPadding = a.getDimensionPixelSize(R.styleable.TryPagerIndicator_tryDividerPadding, dividerTopBottomPadding);
        horizontalPadding = a.getDimensionPixelSize(R.styleable.TryPagerIndicator_tryTabPaddingLeftRight, horizontalPadding);
        tabBackgroundResId = a.getResourceId(R.styleable.TryPagerIndicator_tryTabBackground, 0);
        scrollOffset = a.getDimensionPixelSize(R.styleable.TryPagerIndicator_tryScrollOffset, scrollOffset);
        textAllCaps = a.getBoolean(R.styleable.TryPagerIndicator_tryTextAllCaps, textAllCaps);
        isExpand = a.getBoolean(R.styleable.TryPagerIndicator_tryShouldExpand, isExpand);
        isSame = a.getBoolean(R.styleable.TryPagerIndicator_tryIsSame, isSame);
        tabRule = a.getInt(R.styleable.TryPagerIndicator_tryRule, tabRule);
        a.recycle();
    }

    public void setViewPager(ViewPager pager) {

        this.pager = pager;
        if (pager.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        pager.addOnPageChangeListener(pageListener);
        notifyDataSetChanged();
    }

    /**
     * 更新TryPagerIndicator
     **/
    public void notifyDataSetChanged() {
        //先移除掉所有的View ，防止重复添加
        tabsContainer.removeAllViews();

        tabList.clear();
        int tabCount = pager.getAdapter().getCount();

        if (pager.getAdapter() instanceof IconProvider) {
            for (int i = 0; i < tabCount; i++) {
                Tab tab = new Tab();
                tab.setText(pager.getAdapter().getPageTitle(i).toString());
                tab.setIcon(((IconProvider) pager.getAdapter()).getIcon());
                tab.setTextColor(tabTextColor);
                tab.setRule(tabRule);
                tab.setPosition(i);
                tab.setTextAllCaps(textAllCaps);
                tab.setTextSize(tabTextSize);
                tab.setTabBackgroundResId(tabBackgroundResId);
                tab.setLeftPadding(horizontalPadding);
                tab.setRightPadding(horizontalPadding);
                tab.setTopPadding(verticalPadding);
                tab.setBottomPadding(verticalPadding);
                tab.setSame(isSame);
                addTabView(i, tab);
            }
        } else {
            for (int i = 0; i < tabCount; i++) {
                Tab tab = new Tab();
                tab.setText(pager.getAdapter().getPageTitle(i).toString());
                tab.setTextColor(tabTextColor);
                tab.setRule(tabRule);
                tab.setPosition(i);
                tab.setTextAllCaps(textAllCaps);
                tab.setTextSize(tabTextSize);
                tab.setTabBackgroundResId(tabBackgroundResId);
                tab.setLeftPadding(horizontalPadding);
                tab.setRightPadding(horizontalPadding);
                tab.setTopPadding(verticalPadding);
                tab.setBottomPadding(verticalPadding);
                tab.setSame(isSame);
                addTabView(i, tab);
            }
        }
        updateTabStyles();
        getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                currentPosition = pager.getCurrentItem();
                scrollToChild(currentPosition, 0);
            }
        });
    }

    private void addTabView(final int position, Tab tab) {
        tabList.add(tab);
        TabView tabView = new TabView(getContext(), tab.getRule());
        tabView.setFocusable(true);
        tabView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pager.setCurrentItem(position);
            }
        });
        tabView.setLayoutParams(isExpand ? expandedTabLayoutParams : wrapTabLayoutParams);
        tabsContainer.addView(tabView, position);
    }

    private void updateTabStyles() {
        for (int i = 0; i < tabList.size(); i++) {
            TabView tabView = (TabView) tabsContainer.getChildAt(i);
            if (selectPosition == i) {
                tabList.get(i).setTextColor(tabSelectTextColor);
            } else {
                tabList.get(i).setTextColor(tabTextColor);
            }
            tabView.update(tabList.get(i));
        }
    }

    private void scrollToChild(int position, int offset) {
        if (tabList.size() == 0) {
            return;
        }
        //要滑到的x坐标是被选中的textview的left坐标
        int newScrollX;
        TabView child = (TabView) tabsContainer.getChildAt(position);
        int left = child.getIndicatorLeft();
        if (isSame) {
            newScrollX = left + offset - horizontalPadding;
        } else {
            newScrollX = left + offset;
        }
        //scrollView实际要滑动到的坐标=textview的left坐标-用户设置指示条偏移left坐标的距离
        //在使用中scrollOffset的值还是作用还是比较大的，当用户滑动到左边的边缘，如果左边还有textview未显示出来的话，
        // 有scrollOffset的值，scrollView会向左滑一段距离，以显示出未显示的textview。嗯嗯，可以让用户知道还有textview呢
        if (position > 0 || offset > 0) {
            newScrollX -= scrollOffset;
        }
        if (newScrollX != lastScrollX) {
            lastScrollX = newScrollX;
            scrollTo(newScrollX, 0);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //避免可视化编辑器报错
        if (isInEditMode() || tabList.size() == 0) {
            return;
        }

        final int height = getHeight();

        // draw indicator line
        rectPaint.setColor(indicatorColor);

        // default: line below current tab
        TabView currentTab = (TabView) tabsContainer.getChildAt(currentPosition);
        float lineLeft = currentTab.getIndicatorLeft();
        float lineRight = currentTab.getIndicatorRight();

        // if there is an offset, start interpolating(赋值) left and right coordinates(坐标) between current
        // and next tab
        if (currentPositionOffset > 0f && currentPosition < tabList.size() - 1) {

            TabView nextTab = (TabView) tabsContainer.getChildAt(currentPosition + 1);
            final float nextTabLeft = nextTab.getIndicatorLeft();
            final float nextTabRight = nextTab.getIndicatorRight();

            //假设提示条左坐标：T_left；当前tab的左坐标：C_left；下一个tab的左坐标：N_left；偏移百分比：P
            //计算公式应该是：
            // T_left=C_left+(N_left-C_left)*P
            // T_left=C_left+N_left*P-C_left*P
            // T_left=C_left*(1-P)+N_left
            //嗯，就可以得出下面的计算了
            lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) *
                    lineLeft);
            lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) *
                    lineRight);
        }
        canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);

        // draw underline
        rectPaint.setColor(underlineColor);
        canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);

        // draw divider
        dividerPaint.setColor(dividerColor);
        for (int i = 0; i < tabList.size() - 1; i++) {
            View tab = tabsContainer.getChildAt(i);
            canvas.drawLine(tab.getRight(), dividerTopBottomPadding, tab.getRight(),
                    height - dividerTopBottomPadding, dividerPaint);
        }
    }


    private class PageListener implements OnPageChangeListener {
        /**
         * @param position             当前页面
         * @param positionOffset       偏移的百分比[0,1)(即不包括1)
         * @param positionOffsetPixels 偏移的像素
         **/
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            currentPosition = position;
            currentPositionOffset = positionOffset;
            View child = tabsContainer.getChildAt(position);
            int width = child.getWidth();
            //当前tab的view宽*viewpager偏移百分比=当前tab偏移量
            scrollToChild(position, (int) (positionOffset * width));
            //调用这个方法重新绘制
            invalidate();
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageSelected(int position) {
            selectPosition = position;
            updateTabStyles();
        }
    }


    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        currentPosition = savedState.currentPosition;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPosition = currentPosition;
        return savedState;
    }

    //用来保存状态
    static class SavedState extends BaseSavedState {
        int currentPosition;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPosition = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPosition);
        }

        public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

}
